/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package homeworkhelp.gui;

import homeworkhelp.Course;
import homeworkhelp.Semester;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Trevor
 */
public class testWin extends javax.swing.JFrame {

    EntityManager em = null;
    EntityManagerFactory emf = null;

    private void connectDatabase() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("homework.odb");
        }
        if (em == null) {
            em = emf.createEntityManager();
        }
    }

    private void fillSemesters() {
        semesterCombo.removeAllItems();
        try {
            TypedQuery query = em.createQuery("SELECT s FROM Semester s ORDER BY s.name", Semester.class);
            List semesterList = query.getResultList();
            Object[] semesters = semesterList.toArray();
            DefaultComboBoxModel dcm = new DefaultComboBoxModel(semesters);
            semesterCombo.setModel(dcm);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    private void fillCourses() {
        DefaultListModel dlm = new DefaultListModel();
        dlm.removeAllElements();
        listCourse.setModel(dlm);
        try {
            TypedQuery query = em.createQuery("SELECT c FROM Course c ORDER BY c.name", Course.class);
            List courseList = query.getResultList();
            Object[] cities = courseList.toArray();
            listCourse.setListData(cities);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }

    }

    private void displayCourseDetails() {
        Course course = (Course) listCourse.getSelectedValue();
        if (course != null) {
            courseField.setText(course.getName());
            semesterCombo.setSelectedItem(course.getSemester());
        }
    }

    private void clearCourseDetails() {
        courseField.setText(null);
        semesterCombo.setSelectedItem(null);
    }

    private void setToEdit() {
        courseAdd.setEnabled(false);
        courseEdit.setEnabled(false);
        courseDelete.setEnabled(false);

        listCourse.setEnabled(true);

        courseSave.setEnabled(true);
        courseCancel.setEnabled(true);

        courseField.setEditable(true);
        semesterCombo.setEnabled(true);
    }

    private void setToSelect() {
        courseAdd.setEnabled(true);
        courseEdit.setEnabled(true);
        courseDelete.setEnabled(true);

        listCourse.setEnabled(true);

        courseSave.setEnabled(false);
        courseCancel.setEnabled(false);

        courseField.setEditable(false);
        semesterCombo.setEnabled(false);
    }

    /**
     * Creates new form testWin
     */
    public testWin() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listCourse = new javax.swing.JList();
        courseLabel1 = new javax.swing.JLabel();
        courseAdd = new javax.swing.JButton();
        courseEdit = new javax.swing.JButton();
        courseDelete = new javax.swing.JButton();
        courseLabel2 = new javax.swing.JLabel();
        semesterLabel = new javax.swing.JLabel();
        courseField = new javax.swing.JTextField();
        semesterCombo = new javax.swing.JComboBox();
        courseSave = new javax.swing.JButton();
        courseCancel = new javax.swing.JButton();
        semesterField = new javax.swing.JTextField();
        semesterSave = new javax.swing.JButton();
        closeBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        listCourse.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCourseValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCourse);

        courseLabel1.setText("Courses");

        courseAdd.setText("Add");
        courseAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                courseAddActionPerformed(evt);
            }
        });

        courseEdit.setText("Edit");
        courseEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                courseEditActionPerformed(evt);
            }
        });

        courseDelete.setText("Delete");
        courseDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                courseDeleteActionPerformed(evt);
            }
        });

        courseLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        courseLabel2.setText("Course:");

        semesterLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        semesterLabel.setText("Semester:");

        courseSave.setText("Save");
        courseSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                courseSaveActionPerformed(evt);
            }
        });

        courseCancel.setText("Cancel");
        courseCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                courseCancelActionPerformed(evt);
            }
        });

        semesterSave.setText("Save New Semester");
        semesterSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                semesterSaveActionPerformed(evt);
            }
        });

        closeBtn.setText("Close");
        closeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(courseLabel1)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(courseLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(semesterLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(courseField)
                            .addComponent(semesterCombo, 0, 154, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(courseSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(courseCancel))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(semesterField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(courseAdd)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(courseEdit)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(courseDelete)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(semesterSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(closeBtn)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {courseAdd, courseDelete, courseEdit});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {courseLabel2, semesterLabel});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {courseCancel, courseSave});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(courseLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(courseLabel2)
                            .addComponent(courseField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(semesterLabel)
                            .addComponent(semesterCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(courseSave)
                            .addComponent(courseCancel))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(courseAdd)
                    .addComponent(courseEdit)
                    .addComponent(courseDelete))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(semesterField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(semesterSave)
                    .addComponent(closeBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        connectDatabase();
        fillCourses();
        fillSemesters();
        setToSelect();
    }//GEN-LAST:event_formWindowOpened

    private void semesterSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_semesterSaveActionPerformed
        Semester semester = new Semester();
        semester.setName(semesterField.getText());
        em.getTransaction().begin();
        em.persist(semester);
        em.getTransaction().commit();
        fillSemesters();
        semesterField.setText(null);
    }//GEN-LAST:event_semesterSaveActionPerformed

    private void listCourseValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCourseValueChanged
        displayCourseDetails();
    }//GEN-LAST:event_listCourseValueChanged

    private void courseAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_courseAddActionPerformed
        clearCourseDetails();
        listCourse.clearSelection();
        setToEdit();
        courseField.requestFocus();
    }//GEN-LAST:event_courseAddActionPerformed

    private void courseEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_courseEditActionPerformed
        if (listCourse.getSelectedValue() == null) {
            JOptionPane.showMessageDialog(null, "Select one to edit");
            listCourse.requestFocus();
        } else {
            setToEdit();
            courseField.requestFocus();
            courseField.selectAll();
        }
    }//GEN-LAST:event_courseEditActionPerformed

    private void courseDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_courseDeleteActionPerformed
        Course course = (Course) listCourse.getSelectedValue();
	if (course == null) {
		JOptionPane.showMessageDialog(null, "Select one to delete");
		listCourse.requestFocus();
		return;
	} else {
		em.getTransaction().begin();
		em.remove(course);
		em.getTransaction().commit();
	}
	fillCourses();
	clearCourseDetails();
	setToSelect();
	listCourse.requestFocus();
    }//GEN-LAST:event_courseDeleteActionPerformed

    private void courseSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_courseSaveActionPerformed
        Course city = (Course) listCourse.getSelectedValue();
	if (city == null) {
		city = new Course();
		city.addSemester((Semester) semesterCombo.getSelectedItem());
		city.setName(courseField.getText());
		em.getTransaction().begin();
		em.persist(city);
		em.getTransaction().commit();
	} else {
		city.addSemester((Semester) semesterCombo.getSelectedItem());
		city.setName(courseField.getText());
		em.getTransaction().begin();
		em.getTransaction().commit();
	}
	fillCourses();
	setToSelect();
	listCourse.requestFocus();
    }//GEN-LAST:event_courseSaveActionPerformed

    private void courseCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_courseCancelActionPerformed
        clearCourseDetails();
        setToSelect();
    }//GEN-LAST:event_courseCancelActionPerformed

    private void closeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeBtnActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeBtnActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        em.close();
        emf.close();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(testWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(testWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(testWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(testWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new testWin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeBtn;
    private javax.swing.JButton courseAdd;
    private javax.swing.JButton courseCancel;
    private javax.swing.JButton courseDelete;
    private javax.swing.JButton courseEdit;
    private javax.swing.JTextField courseField;
    private javax.swing.JLabel courseLabel1;
    private javax.swing.JLabel courseLabel2;
    private javax.swing.JButton courseSave;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listCourse;
    private javax.swing.JComboBox semesterCombo;
    private javax.swing.JTextField semesterField;
    private javax.swing.JLabel semesterLabel;
    private javax.swing.JButton semesterSave;
    // End of variables declaration//GEN-END:variables
}
